package zjc.bookkeeping.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.ImageDecoder;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

import zjc.bookkeeping.R;
import zjc.bookkeeping.adapter.ConsumptionListAdapter;
import zjc.bookkeeping.db.ConsumptionBean;
import zjc.bookkeeping.db.DBManager;
import zjc.bookkeeping.homepage.ShowConsumption;
import zjc.bookkeeping.homepage.ShowConsumptionList;
import zjc.bookkeeping.homepage.addpage.AddActivity;
import zjc.bookkeeping.minepage.cClassificationmanagement.ClassificationmanagementMainActivity;
import zjc.bookkeeping.minepage.dAccountbookmanagement.AccountbookmanagementMainActivity;
import zjc.bookkeeping.server.StaticData;
import zjc.bookkeeping.tools.QuotaDialog;
import zjc.bookkeeping.tools.RingView;
import zjc.bookkeeping.tools.ToolsClass;

public class HomeFragment extends Fragment implements View.OnClickListener {
    TextView moneyTv,outcomeTv,incomeTv,timeTv;
    RingView ringView;
    ListView consumptionList;
    LinearLayout addLl;
    RelativeLayout goToRl;
    List<ConsumptionBean> consumptionBeanList;
    ConsumptionListAdapter consumptionListAdapter;
    ArrayAdapter<String> adapter;
    String selectName = "全部";
    String nowTime,oldTime;
    String YMTime = ToolsClass.getYMTime(0);;
    float money,outcomeMoney,incomeMoney;
    int nowValue = 0,afterValue;

    TextView home_tv_money;
    TextView home_tv_monthly_limit;
    TextView home_tv_income_month;
    TextView home_tv_income;
    TextView home_tv_outcome_month;
    TextView home_tv_outcome;
    TextView textView2;
    TextView accountName;
    Button accountBtn;

    ImageButton hone_ib;
    int flag=0;
    int accountId = DBManager.selectAccountId();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home,container,false);
        Log.i("存在",DBManager.findQuota(YMTime)+"");
        if (!DBManager.findQuota(YMTime)){
            DBManager.createQuota(YMTime);
        }
        Log.i("money",money+"");
        money = DBManager.getQuotaMoney(YMTime);
        AutoSizeText(view);
        intiView(view);
        return view;
    }

    //字体大小适应
    private void AutoSizeText(View v){
        home_tv_money=v.findViewById(R.id.home_tv_money);
        home_tv_monthly_limit=v.findViewById(R.id.home_tv_monthly_limit);
        home_tv_income_month=v.findViewById(R.id.home_tv_income_month);
        home_tv_income=v.findViewById(R.id.home_tv_income);
        home_tv_outcome_month=v.findViewById(R.id.home_tv_outcome_month);
        home_tv_outcome=v.findViewById(R.id.home_tv_outcome);
        textView2=v.findViewById(R.id.textView2);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            home_tv_money.setAutoSizeTextTypeUniformWithConfiguration(20,25,1, TypedValue.COMPLEX_UNIT_SP);
            home_tv_monthly_limit.setAutoSizeTextTypeUniformWithConfiguration(10,20,1, TypedValue.COMPLEX_UNIT_SP);
            home_tv_income_month.setAutoSizeTextTypeUniformWithConfiguration(10,20,1, TypedValue.COMPLEX_UNIT_SP);
            home_tv_income.setAutoSizeTextTypeUniformWithConfiguration(20,25,1, TypedValue.COMPLEX_UNIT_SP);
            home_tv_outcome_month.setAutoSizeTextTypeUniformWithConfiguration(10,20,1, TypedValue.COMPLEX_UNIT_SP);
            home_tv_outcome.setAutoSizeTextTypeUniformWithConfiguration(20,25,1, TypedValue.COMPLEX_UNIT_SP);
            textView2.setAutoSizeTextTypeUniformWithConfiguration(20,25,1, TypedValue.COMPLEX_UNIT_SP);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        nowTime = ToolsClass.getYMDTime(1);
        oldTime = ToolsClass.getYMDTime(-7);
        Log.i("accountId",accountId+"--------");
        accountId = DBManager.selectAccountId();
        accountName.setText(DBManager.getAccountName(accountId));
        loadList();
        consumptionListAdapter.notifyDataSetChanged();
        consumptionList.setAdapter(consumptionListAdapter);
        Log.i("nowValue",nowValue + "afterValue："+afterValue);
        ringView.setValue(nowValue,afterValue);
        nowValue = afterValue;
    }
//加载消费信息列表
    private void loadList() {
        outcomeMoney = 0;
        incomeMoney = 0;
        consumptionBeanList = new ArrayList<>();
        Log.i("accountName",accountId+""+",selectName: "+ selectName +",nowTime: "+nowTime+",oldTime: "+oldTime);
        List<ConsumptionBean> list = DBManager.getSpanConsumptionBean(accountId+"",nowTime,oldTime);
        consumptionBeanList.addAll(list);
        consumptionListAdapter = new ConsumptionListAdapter(getContext(),consumptionBeanList);
        for (int i = 0;i<consumptionBeanList.size();i++){
            if (consumptionBeanList.get(i).getConsumption_kind() == 0){
                Log.i("支出第"+i+"次",consumptionBeanList.get(i).getConsumption_money()+"");
                outcomeMoney += consumptionBeanList.get(i).getConsumption_money();
                Log.i("支出第"+i+"次",outcomeMoney+"");
            }
            if (consumptionBeanList.get(i).getConsumption_kind() == 1){
                Log.i("收入第"+i+"次",consumptionBeanList.get(i).getConsumption_money()+"");
                incomeMoney += consumptionBeanList.get(i).getConsumption_money();
                Log.i("收入第"+i+"次",incomeMoney+"");
            }
        }
        afterValue = (int) (outcomeMoney / money * 100);
        Log.i("afterValue",afterValue+"");
        DecimalFormat df = new DecimalFormat("#0.00");// 保留两位小数
        moneyTv.setText(df.format(money - outcomeMoney));
        Log.i("outcomeMoney",outcomeMoney+"");
        Log.i("incomeMoney",incomeMoney+"");
        outcomeTv.setText(outcomeMoney+"");
        incomeTv.setText(incomeMoney+"");

        if((money - outcomeMoney<100||(outcomeMoney>3*incomeMoney&&incomeMoney!=0))&&flag==0){
                hone_ib.setVisibility(View.VISIBLE);
                //动图
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                    try {
                        //利用Android9.0新增的ImageDecoder读取gif动画
                        ImageDecoder.Source source = ImageDecoder.createSource(getResources(), R.drawable.tip);
                        //从数据源中解码得到gif图形数据
                        Drawable drawable = ImageDecoder.decodeDrawable(source);
                        //设置图像视图的图形为gif图片
                        hone_ib.setImageDrawable(drawable);
                        //如果是动画图形，则开始播放动画
                        if (drawable instanceof Animatable) {
                            Animatable animatable = (Animatable) hone_ib.getDrawable();
                            animatable.start();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
            }
        }else {
            hone_ib.setVisibility(View.GONE);
        }
    }

    private void intiView(View view) {
        accountName = view.findViewById(R.id.home_account_name);

        timeTv = view.findViewById(R.id.home_tv_month);
        timeTv.setText(YMTime.substring(5,8));
        moneyTv = view.findViewById(R.id.home_tv_money);

        outcomeTv = view.findViewById(R.id.home_tv_outcome);
        incomeTv = view.findViewById(R.id.home_tv_income);
        addLl = view.findViewById(R.id.home_ll_add);
        goToRl = view.findViewById(R.id.home_rl_go_to);
        ringView = view.findViewById(R.id.home_rv_ring);
        consumptionList = view.findViewById(R.id.home_lv_list);

        hone_ib=view.findViewById(R.id.hone_ib);
        accountBtn=view.findViewById(R.id.home_account_btn);

        accountBtn.setOnClickListener(this);
        addLl.setOnClickListener(this);
        goToRl.setOnClickListener(this);
        ringView.setOnClickListener(this);
        hone_ib.setOnClickListener(this);
        consumptionList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent();
                intent.putExtra("consumptionBean", consumptionBeanList.get(i));
                intent.setClass(getContext(), ShowConsumption.class);
                startActivity(intent);
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.home_ll_add:
                Intent intent = new Intent(getActivity(),AddActivity.class);
                startActivity(intent);
                break;
            case R.id.home_rv_ring:
                showQuotaDialog();
                break;
            case R.id.home_rl_go_to:
                Intent listActivity = new Intent(getActivity(), ShowConsumptionList.class);
                startActivity(listActivity);
                break;
            case R.id.hone_ib:
                Log.i("hone_ib","被点击了");
                consumptiontip();
                break;
            case R.id.home_account_btn:
                Intent intent1 = new Intent(getActivity(), AccountbookmanagementMainActivity.class);
                startActivity(intent1);
                break;
        }
    }

    private void showQuotaDialog() {
        QuotaDialog quotaDialog = new QuotaDialog(getContext());
        quotaDialog.show();
        quotaDialog.getMoney(money);
        quotaDialog.setOnQuotaSureListener(new QuotaDialog.OnQuotaSureListener() {
            @Override
            public void onQuotaSure() {
                String str = quotaDialog.getQuotaEt();
                money = Float.parseFloat(str);
                DBManager.updateQuota(money,YMTime);
                afterValue = (int) (outcomeMoney / money * 100);
                Log.i("afterValue",afterValue+"");
                incomeMoney = money - outcomeMoney;
                incomeTv.setText(Float.toString(incomeMoney));
                ringView.setValue(nowValue,afterValue);
                nowValue = afterValue;
            }
        });
    }
//消费提醒
    private void consumptiontip(){
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setIcon(R.drawable.tip);
        float money= Float.parseFloat(moneyTv.getText().toString());
        float inmoney= Float.parseFloat(incomeTv.getText().toString());
        float outmoney=Float.parseFloat(outcomeTv.getText().toString());
        if(money<100){
            builder.setTitle("额度不足提醒");
            builder.setMessage("注意注意，你定下的本月额度要用完啦，适当消费哦！");
        }else if (outmoney>3*inmoney){
            builder.setTitle("收支不良提醒");
            builder.setMessage("注意注意，你这个月的支出远远超过收入了，适当消费哦！");
        }
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                hone_ib.setVisibility(View.GONE);
                flag=1;
            }
        });
        builder.show();
    }

}